/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.just.dusin.ooii.component.kj;

import gnu.io.CommPortIdentifier;
import gnu.io.NoSuchPortException;
import gnu.io.PortInUseException;
import gnu.io.SerialPort;
import gnu.io.UnsupportedCommOperationException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.LinkedList;
import java.util.Properties;
import java.util.Queue;
import java.util.logging.Level;
import org.apache.log4j.Logger;
import org.dusin.webcoal.exception.OOIIException;
import org.just.dusin.ooii.component.Source;
import org.just.dusin.ooii.util.DeviceData;

/**
 *
 * @author Administrator
 */
public class VirtueKJ215Source extends Source {

    private static Logger logger = Logger.getLogger(VirtueKJ215Source.class.getName());    
    
    private int beltSpeed = 1;      //皮带速度
    private int flowSpeed = 500;    //流量
    private double total = 0;          //仪表读数
    private int inteval = 2000; //循环延时
    
    private long timer;
    
    private int no=1;   //设备编号
    private double  propabilityOfNoResponse =  0.001;  //设备无数据返回概率
    private double  propabilityOfWrongResponse =0.001;   //设备返回错误数据概率
    private Queue<Integer> shiftQueue = new LinkedList<Integer>();    //最近10次采集数据的成功 与失败，为了得到采集数据是否正常
    private double preTotal = -1;
    
    //获取当前采集数据的成功率
    public int getSuccRate(){
        int r=0;
        for(Integer i:shiftQueue){
            if(i==1)
                r++;
        }
        return r;
    }
    
    //将当前是否成功的状态置入对列
    private void addQueue(int s){
        if(shiftQueue.size()>=10){
            shiftQueue.poll();
        }
        shiftQueue.add(s);
    }   

    public int getInteval() {
        return inteval;
    }

    public void setInteval(int inteval) {
        this.inteval = inteval;
    }

    public int getNo() {
        return no;
    }

    public void setNo(int no) {
        this.no = no;
    }
    
    
    @Override
    public void initComponent(Properties props) {        
    }

    @Override
    public void destroyComponent() throws Exception {        
    }

    @Override
    public void run() {        
        
        timer = System.currentTimeMillis();
        
        while (!stop) {
            try {                
                String msg;
                if (Math.random() > this.propabilityOfNoResponse) {                    
                    
                    //System.out.println();
                    if(Math.random()>this.propabilityOfWrongResponse){
                        long now = System.currentTimeMillis();
                        long  timeElapsed = now - timer;                       
                        timer = now;                        
                        
                        double cFlowSpeed = this.flowSpeed*(1+(Math.random()*0.05-0.025));
                        double cBeltSpeed = this.beltSpeed*(1+(Math.random()*0.05-0.025));
                        this.total = this.total+cFlowSpeed*timeElapsed/(60*60*1000);                        
                        byte shellOpen = 1;
                        if(Math.abs(preTotal+1)<1e-6||Math.abs(total-preTotal)<60) { //对获取的数据进行监测
                            msg= DataPackage.packYBSJ(no,total,cFlowSpeed,cBeltSpeed,shellOpen,0);
                            preTotal= total;
                            addQueue(0);
                        }
                        else{
                            msg = DataPackage.packYBSJ(no,0,0,0,(byte)0,2);  //2表示有回应数据，但数据异常
                            addQueue(1);
                        }
                    }else{
                        msg = DataPackage.packYBSJ(no,0,0,0,(byte)0,2);  //2表示有回应数据，但数据异常
                        addQueue(1);
                        logger.error("仪表数据异常");
                    }                        
                }else{                    
                    msg = DataPackage.packYBSJ(no,0,0,0,(byte)0,1); //1表示指令发送，设备无响应
                    addQueue(1);
                    logger.error("仪表无数据返回");
                }                
                logger.info("处理消息"+msg);
                sink.process(msg);      //处理正常数据
            } catch (OOIIException ex) {
                ex.printStackTrace();
                logger.error("目的组件异常"+ex.getMessage());
            } finally{
                try {
                    Thread.sleep(this.inteval);
                } catch (InterruptedException ex) {
                    logger.error("睡眠中断");
                }
            }
        }
    }
}
